package com.chapter8.example1;

/**
 * 工厂方法模式：
 * 简单工厂模式把判断的逻辑写在了工厂类中，违背了开放封闭原则
 * 工厂方法模式使一个类的实例化延迟到其子类，增加新的运算时，需要增加对应的运算类和工厂，但不需要修改代码
 * 工厂方法模式实现时，客户端需要决定实例化哪一个工厂来实现运算类，选择判断的问题还是存在的。
 */
public class Main {
    public static void main(String[] args) throws Exception {
        IFactory addFactory = new AddFactory();
        final Operation opetation = addFactory.createOpetation();
        opetation.setNumberA(10);
        opetation.setNumberB(20);
        double result = opetation.getResult();
        System.out.println(result);
    }
}

abstract class Operation {
    private double numberA;
    private double numberB;

    public double getNumberA() {
        return numberA;
    }

    public void setNumberA(double numberA) {
        this.numberA = numberA;
    }

    public double getNumberB() {
        return numberB;
    }

    public void setNumberB(double numberB) {
        this.numberB = numberB;
    }

    public abstract double getResult() throws Exception;
}


class OperationAdd extends Operation {
    @Override
    public double getResult() {
        return super.getNumberA() + super.getNumberB();
    }
}

class OperationSub extends Operation {

    @Override
    public double getResult() {
        return super.getNumberA() - super.getNumberB();
    }
}

class OperationMul extends Operation {

    @Override
    public double getResult() {
        return super.getNumberA() * super.getNumberB();
    }
}

class OperationDiv extends Operation {

    @Override
    public double getResult() throws Exception {
        if(super.getNumberB() == 0){
            throw new Exception("除数不能为0！");
        }
        return  super.getNumberA() / super.getNumberB();
    }
}